﻿using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WMS.Model;
using WMS.Repository.IRepository;

namespace WMS.Repository
{
    public class UserRepository : BaseRepository<UserModel>, IUserRepository
    {
        public UserRepository(ISqlSugarClient db, ILogger<UserRepository> logger) : base(db, logger)
        {
        }

        /// <summary>
        /// 用户分页模糊查询
        /// </summary>
        public async Task<PageResult<UserModel>> GetUserPagedListAsync(UserQueryRequest request)
        {
            try
            {
                var query = _db.Queryable<UserModel>();

                // 添加模糊查询条件
                if (!string.IsNullOrEmpty(request.Account))
                    query = query.Where(u => u.Account.Contains(request.Account));

                if (!string.IsNullOrEmpty(request.Realname))
                    query = query.Where(u => u.Realname.Contains(request.Realname));

                if (!string.IsNullOrEmpty(request.Email))
                    query = query.Where(u => u.Email.Contains(request.Email));

                if (!string.IsNullOrEmpty(request.Phone))
                    query = query.Where(u => u.Phone.Contains(request.Phone));

                // 精确匹配状态
                if (request.Status.HasValue)
                    query = query.Where(u => u.Status == request.Status.Value);

                // 按创建时间倒序
                query = query.OrderBy(u => u.Id, OrderByType.Asc);

                // 执行分页查询
                RefAsync<int> totalCount = 0;
                var data = await query.ToPageListAsync(request.PageIndex, request.PageSize, totalCount);

                return new PageResult<UserModel>
                {
                    PageIndex = request.PageIndex,
                    PageSize = request.PageSize,
                    TotalCount = totalCount,
                    TotalPages = (int)Math.Ceiling(totalCount / (double)request.PageSize),
                    Data = data
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"用户分页查询失败 - 账号: {request.Account}, 姓名: {request.Realname}, 邮箱: {request.Email}, 状态: {request.Status}, 页码: {request.PageIndex}, 页大小: {request.PageSize}");
                throw;
            }
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        public async Task<bool> AddUserAsync(UserModel userModel)
        {
            try
            {
                return await _db.Insertable(userModel).ExecuteCommandAsync() > 0;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加用户失败 - 账号: {userModel?.Account}, 姓名: {userModel?.Realname}");
                throw;
            }
        }

        /// <summary>
        /// 查询账号是否存在
        /// </summary>
        public async Task<UserModel> GetAccountAsync(string account)
        {
            try
            {
                return await _db.Queryable<UserModel>().Where(x => x.Account == account).FirstAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"查询账号失败 - 账号: {account}");
                throw;
            }
        }

        /// <summary>
        /// 查询邮箱是否存在
        /// </summary>
        public async Task<UserModel> GetEmailAsync(string email)
        {
            try
            {
                return await _db.Queryable<UserModel>().Where(x => x.Email == email).FirstAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"查询邮箱失败 - 邮箱: {email}");
                throw;
            }
        }

        /// <summary>
        /// 获取全部用户
        /// </summary>
        public async Task<List<UserModel>> QueryAsync()
        {
            try
            {
                return await _db.Queryable<UserModel>().ToListAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取全部用户失败");
                throw;
            }
        }

        /// <summary>
        /// 获取用户下拉框
        /// </summary>
        public async Task<List<UserModel>> GetUserDropdownBoxAsync()
        {
            try
            {
                return await _db.Queryable<UserModel>().ToListAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户下拉框失败");
                throw;
            }
        }
    }
}